package com.springbootblog.utils;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

public class RabbitUtils {
    public static String ip;
    @Value("${spring.rabbitmq.host}")
    public static void setIp(String ip) {
        RabbitUtils.ip = ip;
    }
    public static Integer port;
    @Value("${spring.rabbitmq.port}")
    public static void setPort(Integer port) {
        RabbitUtils.port = port;
    }
    public static String username;
    @Value("${spring.rabbitmq.username}")
    public static void setUsername(String username) {
        RabbitUtils.username = username;
    }
    public static String password;
    @Value("${spring.rabbitmq.password}")
    public static void setPassword(String password) {
        RabbitUtils.password = password;
    }

    private static ConnectionFactory connectionFactory = new ConnectionFactory();
    static {
        connectionFactory.setHost(RabbitUtils.ip);
        connectionFactory.setPort(RabbitUtils.port);//5672是RabbitMQ的默认端口号
        connectionFactory.setUsername(RabbitUtils.username);
        connectionFactory.setPassword(RabbitUtils.password);
    }
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = connectionFactory.newConnection();
            return conn;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
